#!/bin/bash

# MatrixOne Performance Test Script
set -e

echo "Starting MatrixOne performance tests..."

# Set variables
DB_HOST=${DB_HOST:-127.0.0.1}
DB_PORT=6001
DB_USER="root"
DB_PASSWORD="111"
DB_NAME="test"
RESULTS_DIR="/home/data/database/test_results"
mkdir -p $RESULTS_DIR

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
MATRIXONE_RESULT_FILE="$RESULTS_DIR/matrixone_perf_$TIMESTAMP.log"

echo "MatrixOne Performance Test - $TIMESTAMP" > $MATRIXONE_RESULT_FILE
echo "========================================" >> $MATRIXONE_RESULT_FILE

# Build mysql command with password
MYSQL_CMD="mysql -h $DB_HOST -P $DB_PORT -u $DB_USER -p$DB_PASSWORD"

# Test connection
echo "Testing connection to MatrixOne..." | tee -a $MATRIXONE_RESULT_FILE
if ! $MYSQL_CMD -e "SELECT 1;" > /dev/null 2>&1; then
  echo "Error: Could not connect to MatrixOne" | tee -a $MATRIXONE_RESULT_FILE
  echo "Please check if MatrixOne is running and accessible." | tee -a $MATRIXONE_RESULT_FILE
  exit 1
fi

echo "Great! Successfully connected to MatrixOne" | tee -a $MATRIXONE_RESULT_FILE

# Test 1: Basic connection and version
echo "1. Testing basic connection..." | tee -a $MATRIXONE_RESULT_FILE
$MYSQL_CMD -e "SELECT VERSION();" >> $MATRIXONE_RESULT_FILE 2>&1
echo "Basic connection test completed" | tee -a $MATRIXONE_RESULT_FILE

# Test 2: Create test database and tables
echo "2. Creating test database and tables..." | tee -a $MATRIXONE_RESULT_FILE
$MYSQL_CMD -e "
CREATE DATABASE IF NOT EXISTS $DB_NAME;
USE $DB_NAME;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100),
  age INT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
  id INT,
  user_id INT,
  amount DECIMAL(10,2),
  order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
" >> $MATRIXONE_RESULT_FILE 2>&1

echo "Database and table creation completed" | tee -a $MATRIXONE_RESULT_FILE

# Test 3: Data insertion performance
echo "3. Testing data insertion performance..." | tee -a $MATRIXONE_RESULT_FILE
START_TIME=$(date +%s.%N)

# Insert sample data (1000 records) - using batch insert for better performance
INSERT_SQL="USE $DB_NAME; INSERT INTO users (name, email, age) VALUES "
for i in $(seq 1 1000); do
  INSERT_SQL+="('user_$i', 'user_$i@example.com', $((20 + RANDOM % 50)))"
  if [ $i -ne 1000 ]; then
    INSERT_SQL+=","
  fi
done
INSERT_SQL+=";"

$MYSQL_CMD -e "$INSERT_SQL" >> $MATRIXONE_RESULT_FILE 2>&1

END_TIME=$(date +%s.%N)
INSERT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Insertion time for 1000 records: $INSERT_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Test 4: Query performance
echo "4. Testing query performance..." | tee -a $MATRIXONE_RESULT_FILE

# Query 1: Simple COUNT
START_TIME=$(date +%s.%N)
$MYSQL_CMD -e "USE $DB_NAME; SELECT COUNT(*) FROM users;" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY1_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Count query time: $QUERY1_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Query 2: Conditional SELECT
START_TIME=$(date +%s.%N)
$MYSQL_CMD -e "USE $DB_NAME; SELECT * FROM users WHERE age > 30 LIMIT 10;" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY2_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Conditional query time: $QUERY2_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Query 3: JOIN query
START_TIME=$(date +%s.%N)
$MYSQL_CMD -e "USE $DB_NAME; 
-- Insert some order data first
INSERT INTO orders (user_id, amount) 
SELECT id, RAND() * 1000 
FROM users LIMIT 100;

SELECT u.id, u.name, COUNT(o.id) as order_count 
FROM users u 
LEFT JOIN orders o ON u.id = o.user_id 
GROUP BY u.id, u.name 
LIMIT 5;
" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY3_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "JOIN query time: $QUERY3_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Query 4: Aggregation query
START_TIME=$(date +%s.%N)
$MYSQL_CMD -e "USE $DB_NAME; SELECT AVG(age) as avg_age, MAX(age) as max_age, MIN(age) as min_age FROM users;" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY4_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Aggregation query time: $QUERY4_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Test 5: Update performance
echo "5. Testing update performance..." | tee -a $MATRIXONE_RESULT_FILE
START_TIME=$(date +%s.%N)
$MYSQL_CMD -e "USE $DB_NAME; UPDATE users SET age = age + 1 WHERE id <= 100;" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
UPDATE_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Update time for 100 records: $UPDATE_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Test 6: Complex analytical query
echo "6. Testing complex analytical query..." | tee -a $MATRIXONE_RESULT_FILE
START_TIME=$(date +%s.%N)
# MatrixOne may not support window functions, use alternative complex query
$MYSQL_CMD -e "USE $DB_NAME; 
SELECT 
  age_range,
  COUNT(*) as user_count,
  AVG(age) as avg_age_in_range
FROM (
  SELECT 
    id,
    name,
    age,
    CASE 
      WHEN age < 30 THEN 'Under 30'
      WHEN age BETWEEN 30 AND 50 THEN '30-50'
      ELSE 'Over 50'
    END as age_range
  FROM users
) age_groups
GROUP BY age_range
ORDER BY user_count DESC;
" >> $MATRIXONE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
COMPLEX_QUERY_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Complex analytical query time: $COMPLEX_QUERY_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Test 7: Concurrent query test
echo "7. Testing concurrent queries..." | tee -a $MATRIXONE_RESULT_FILE
START_TIME=$(date +%s.%N)
for i in $(seq 1 5); do
  $MYSQL_CMD -e "USE $DB_NAME; SELECT COUNT(*) FROM users WHERE age > $((30 + i));" >> $MATRIXONE_RESULT_FILE 2>&1 &
done
wait
END_TIME=$(date +%s.%N)
CONCURRENT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Concurrent query time: $CONCURRENT_TIME seconds" | tee -a $MATRIXONE_RESULT_FILE

# Test 8: Resource usage
echo "8. Checking resource usage..." | tee -a $MATRIXONE_RESULT_FILE
docker stats matrixone-test --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" >> $MATRIXONE_RESULT_FILE 2>&1

# Test 9: Database statistics
echo "9. Checking database statistics..." | tee -a $MATRIXONE_RESULT_FILE
$MYSQL_CMD -e "USE $DB_NAME; SHOW TABLES;" >> $MATRIXONE_RESULT_FILE 2>&1

# Summary
echo "" >> $MATRIXONE_RESULT_FILE
echo "Performance Test Summary" >> $MATRIXONE_RESULT_FILE
echo "=======================" >> $MATRIXONE_RESULT_FILE
echo "Insertion Performance: $INSERT_TIME seconds for 1000 records" >> $MATRIXONE_RESULT_FILE
echo "Count Query: $QUERY1_TIME seconds" >> $MATRIXONE_RESULT_FILE
echo "Conditional Query: $QUERY2_TIME seconds" >> $MATRIXONE_RESULT_FILE
echo "JOIN Query: $QUERY3_TIME seconds" >> $MATRIXONE_RESULT_FILE
echo "Aggregation Query: $QUERY4_TIME seconds" >> $MATRIXONE_RESULT_FILE
echo "Complex Analytical Query: $COMPLEX_QUERY_TIME seconds" >> $MATRIXONE_RESULT_FILE
echo "Update Performance: $UPDATE_TIME seconds for 100 records" >> $MATRIXONE_RESULT_FILE
echo "Concurrent Queries: $CONCURRENT_TIME seconds for 5 queries" >> $MATRIXONE_RESULT_FILE
echo "Test completed at: $(date)" >> $MATRIXONE_RESULT_FILE

echo ""
echo "MatrixOne performance test completed!"
echo "Results saved to: $MATRIXONE_RESULT_FILE"